/*
 * Project: Sudoku Hint Engine for Android
 * Copyright (C) 2010-2013 Emanuel Moecklin
 * 
 * Available under the terms of the Lesser General Public License (LGPL)
 */
package com.onegravity.sudoku.solver.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;

import android.util.Log;

public class Logger {

	private static final int QUEUE_SIZE = 50;
	private static ConcurrentLinkedQueue<String> logEntries = new ConcurrentLinkedQueue<String>();

	private static final String DATE_FORMAT_NOW = "dd-MM-yyyy HH-mm-ss-SSS"; //$NON-NLS-1$
	private static final SimpleDateFormat SDF = new SimpleDateFormat(DATE_FORMAT_NOW);

	public static Collection<String> getLoggedEntries() {
		return logEntries;
	}
	
	public static void v(String tag, String msg) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.VERBOSE)) {
			Log.v(tag, msg);
		}
	}

	public static void d(String tag, String msg) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.DEBUG)) {
			Log.d(tag, msg);
		}
	}

	public static void i(String tag, String msg) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.INFO)) {
			Log.i(tag, msg);
		}
	}

	public static void w(String tag, String msg) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.WARN)) {
			Log.w(tag, msg);
		}
	}

	public static void w(String tag, String msg, Throwable t) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.WARN)) {
			Log.w(tag, msg, t);
		}
	}

	public static void e(String tag, String msg) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.ERROR)) {
			Log.e(tag, msg);
		}
	}

	public static void e(String tag, String msg, Throwable t) {
		tag = checkTag(tag);
		cacheEntry(tag, msg);
		if (Log.isLoggable(tag, Log.ERROR)) {
			Log.e(tag, msg, t);
		}
	}

	private static String checkTag(String tag) {
		return (tag.length()>23) ? tag.substring(0, 23) : tag;
	}
	
	private static void cacheEntry(String tag, String msg) {
		if (logEntries.size()==QUEUE_SIZE) logEntries.poll();
		logEntries.add(now() + "  " + tag + ": " + msg); //$NON-NLS-1$ //$NON-NLS-2$
	}
	
    private static String now() {
		Calendar cal = Calendar.getInstance();
		return SDF.format(cal.getTime());
	}

}
